package com.basic.greedy;

import lombok.AllArgsConstructor;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * BackPackQuestion.. 贪心之背包问题
 *
 * @author Lizhong
 * @date 2019/10/10
 */
public class BackPackQuestion {
    /**
     * wi = [35,30,60,50,40,10,25]
     * pi = [10,40,30,50,35,40,30]
     *
     *
     * 总重量不超过C
     *
     */
    static int[] w = {35, 30, 60, 50, 40, 10, 25};
    static int[] p = {10, 40, 30, 50, 35, 40, 30};
    static List<BackPack> list = new ArrayList<>();

    static {
        for (int i = 0; i < w.length; i++) {
            list.add(new BackPack(w[i], p[i], 0));
        }
    }

    /**
     * 第一按照重量从小到大排序，
     * @param C
     */
    public static void byWeight(int C) {
        int maxP = 0;
        int maxW = 0;
        list.sort(Comparator.comparingDouble(val -> val.w));
        for (int i = 0; i < list.size(); i++) {
            BackPack backPack = list.get(i);
            if (maxW + backPack.w <= C) {
                maxW += backPack.w;
                maxP += backPack.p;
                backPack.flag = 1;
            } else {
                System.out.println(maxW + " : " + maxP);
                return;
            }
            ;
        }

    }

    /**
     * 按照价值从大到小排序
     * @param C
     */
    public static void byPrice(int C) {
        int maxP = 0;
        int maxW = 0;
        // list.sort(Comparator.comparingInt(val->val.p));
        list.sort((val, v) -> val.p >= v.p ? -1 : 1);
        for (int i = 0; i < list.size(); i++) {
            BackPack backPack = list.get(i);
            if (maxW + backPack.w <= C) {
                maxW += backPack.w;
                maxP += backPack.p;
                backPack.flag = 1;
            } else {
                System.out.println(maxW + " : " + maxP);
                return;
            }
            ;
        }
    }

    public static void byPriceDivideWeight(int C) {
        int maxP = 0;
        int maxW = 0;
        // list.sort(Comparator.comparingInt(val->val.p));
        list.sort((val, v) -> val.p / val.w >= v.p / v.w ? -1 : 1);
        for (int i = 0; i < list.size(); i++) {
            BackPack backPack = list.get(i);
            if (maxW + backPack.w <= C) {
                maxW += backPack.w;
                maxP += backPack.p;
                backPack.flag = 1;
            }

            ;
        }
        System.out.println(maxW + " : " + maxP);
    }


    public static void main(String[] args) {
        byWeight(150);
        byPrice(150);
        byPriceDivideWeight(150);
    }

    @AllArgsConstructor
    static class BackPack {
        double w;
        double p;
        int flag; // 1 占有，2 不符合要求

    }


}
